package cn.blnp.net.flowable.boot.config.flowable;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.cfg.multitenant.TenantInfoHolder;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.impl.cfg.multitenant.MultiSchemaMultiTenantProcessEngineConfiguration;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <h3>多数据源与多租户的关系管理配置</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/9 19:39
 */
@Getter
@Slf4j
public class MultiTenantDataSourceProcessConfig extends MultiSchemaMultiTenantProcessEngineConfiguration {

    @Setter
    private Map<String, DataSource> tenantDataSourceRelationMap = new ConcurrentHashMap<>();

    public MultiTenantDataSourceProcessConfig(TenantInfoHolder tenantInfoHolder) {
        super(tenantInfoHolder);
    }

    @Override
    public ProcessEngine buildProcessEngine() {
        log.warn("===开始构建多数据源与多租户关系===");
        //将租户与对应数据源进行关系绑定
        for (String tenantId : tenantInfoHolder.getAllTenants()) {
            DataSource source = tenantDataSourceRelationMap.get(tenantId);
            if (null == source) {
                continue;
            }
            this.registerTenant(tenantId, source);
        }
        return super.buildProcessEngine();
    }
}
